package com.ray.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.ray.bean.CompanyBean;
import com.ray.bean.PermissionBean;
import com.ray.bean.RoleBean;
import com.ray.bean.UserBean;
import com.ray.mapper.PermissionMapper;
import com.ray.pojo.MyUser;
import com.ray.util.ReturnStringUtil;
import com.ray.util.StringUtil;

import net.sf.json.JSONArray;

@Service
public class PermissionService {
	@Autowired
	PermissionMapper permissionMapper;
	@Autowired 
	UserService userService;
	@Autowired
	CompanyService companyService;

	//添加权限
	public void addPermission(PermissionBean permissionBean) {
		String uuid=StringUtil.getUUID();
		permissionBean.setId(uuid);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		permissionBean.setCreateTime(sdf.format(new Date()));
		permissionMapper.addPermission(permissionBean);
	}

	//查询所有权限
	public List<PermissionBean> querryAllPermission() {
		return permissionMapper.querryAllPermission();
	}
	
    //修改权限
	public void updatePermission(PermissionBean permissionBean) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		permissionBean.setCreateTime(sdf.format(new Date()));
		permissionMapper.updatePermission(permissionBean);
	}

	//获取所有角色
	public List<RoleBean> querryAllrole(String companyid) {
		// TODO Auto-generated method stub
		return permissionMapper.querryAllrole(companyid);
	}

	//添加角色
	public void addRole(RoleBean roleBean) {
		roleBean.setId(StringUtil.getUUID());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		roleBean.setCreateTime(sdf.format(new Date()));
		permissionMapper.addRole(roleBean);
	}

	//获取角色的权限
	public List<PermissionBean> getRolePermission(String roleId,Map map) {
		CompanyBean companyBean=companyService.getCompany(map);
        //获取角色关联的权限id
		List<String> permissionIdList=this.getPermissionIdByRoleID(roleId,companyBean.getStatus());
		if(null==permissionIdList||permissionIdList.size()<=0) {
			return null;
		}
		List<PermissionBean> perList=permissionMapper.querryPermissionByIdList(permissionIdList,companyBean.getStatus());
		return perList;
	}
	
	//获取角色为拥有权限id
   public List<String> getPermissionIdByRoleID(String roleId, int status){
	   return permissionMapper.getPermissionIdByRoleID(roleId,status);
   }
   
   
    //获取角色没有的权限
	public List<PermissionBean> getRoleNoPermission(String roleId, Map map) {
		CompanyBean  companyBean=companyService.getCompany(map);
		//获取角色关联的权限id
		List<String> permissionIdList=this.getPermissionIdByRoleID(roleId,companyBean.getStatus());
		List<PermissionBean> perList=permissionMapper.querryNoPermissionByIdList(permissionIdList,companyBean.getStatus());
		return perList;
	}

	//添加角色权限
	public void addRolePermission(String roleId,String permissionIdArray) {
		 JSONArray jsonArray = JSONArray.fromObject(permissionIdArray);
		 List<String> titleLists=jsonArray.subList(0, jsonArray.size());
		 this.addRolePermission(roleId, titleLists);
	}
	public void addRolePermission(String roleId,List<String> titleLists) {
		permissionMapper.addRolePermission(roleId,titleLists);
	}

	//移除角色权限
	public void removePermission(String roleId, String permissionIdArray) {
		 Assert.isTrue(this.checkRegisterUser(roleId),"此角色关联注册人，不可移除权限");
		 JSONArray jsonArray = JSONArray.fromObject(permissionIdArray);
		 List<String> titleLists=jsonArray.subList(0, jsonArray.size());
		 permissionMapper.removePermission(roleId,titleLists);
	}
	
	/**
	 * 校验角色是否关联注册人
	 * @param roleId(角色id)
	 * @return
	 */
    private boolean checkRegisterUser(String roleId) {
    	boolean bool=false;
    	List<String> listStr=permissionMapper.checkRegisterUser(roleId);
    	if(listStr==null || listStr.size()<=0) {
    		bool=true;
    	}
		return bool;
	}

	//获取用户角色
	public List<RoleBean> getUserRole(Map map) {
		return permissionMapper.getUserRole(map);
	}
	//获取用户没有的角色
	public List<RoleBean> getUserNoRole(Map map) {
		return permissionMapper.getUserNoRole(map);
	}

	//添加用户角色
	public void addUserRole(String userId, String roleIdArray) {
		 JSONArray jsonArray = JSONArray.fromObject(roleIdArray);
		 List<String> titleLists=jsonArray.subList(0, jsonArray.size());
		 this.addUserRole(userId, titleLists);
	}
	public void addUserRole(String userId, List<String> titleLists) {
			MyUser myUser=new MyUser();
			myUser.setUserId(userId);
	        myUser=userService.getUser(myUser);
	        Assert.notNull(myUser,"该用户不存在");
	        Assert.isTrue(myUser.getIsManager()!=1,"注册人角色不可更改");
		 permissionMapper.addUserRole(userId,titleLists);
	}
	
    //移除用户角色
	public void removeUserRole(String userId, String roleIdArray) {
		MyUser myUser=new MyUser();
		myUser.setUserId(userId);
        myUser=userService.getUser(myUser);
        Assert.notNull(myUser,"该用户不存在");
        Assert.isTrue(myUser.getIsManager()!=1,"注册人角色不可更改");
		JSONArray jsonArray = JSONArray.fromObject(roleIdArray);
		List<String> titleLists=jsonArray.subList(0, jsonArray.size());
		permissionMapper.removeUserRole(userId,titleLists);
	}
	
	//通过url后去权限
	public PermissionBean getPermissionByUrl(String url) {
		return permissionMapper.getPermissionByUrl(url);
	}
	
	/**
	 * 通过用户id获取用户权限
	 * @param userId 用户id
	 * @return
	 */
	public List<PermissionBean> getUserPermissionBeanByUserId(String userId){
		return permissionMapper.getUserPermissionBeanByUserId(userId);
	}
	
	//获取所有权限id
	public List<String> getPermissionIdList(){
		return permissionMapper.getPermissionIdList();
	}
	
	/*
	 * 获取所有免费权限
	 */
	public List<String> getPermissionIdListNotPay() {
		return permissionMapper.getPermissionIdListNotPay();
	}

	//删除角色
	public void deleteRole(Map map) {
		permissionMapper.deleteRole(map);	
	}

	//修改角色信息
	public void updateRole(Map map) {
		permissionMapper.updateRole(map);	
	}

	/**
	 * 设置
	 * @param roleId
	 * @param userId
	 * @param request
	 */
	public void setUserRolePermission(String roleId,MyUser myUser, HttpServletRequest request) {
		 Map map=new HashMap<>();
		 map.put("loginCompany", myUser.getCompany());
		 map.put("userId", myUser.getUserId());
	     List<RoleBean> listStr=permissionMapper.getUserRole(map);
	     if(listStr!=null && listStr.size()>0) {
	    	 for(RoleBean role:listStr) {
	    		 if(role.getId().equals(roleId)) {
	    			 myUser.setPermissionList(this.getUserPermissionBeanByUserId(myUser.getUserId()));
	    			 request.getSession().setAttribute("userLogin", myUser);
	    			 break;
	    		 }
	    	 }
	     }
		 
	}

	/**
	 * 获取拥有此角色的用户
	 * @param map
	 * @return
	 */
	public List<UserBean> getRoleUser(Map map) {
		StringUtil.checkIsTrue(map, "roleId", "未获取到角色id");
		return permissionMapper.getRoleUser(map);
	}

	/**
	 * 获取公司权限
	 * @param map
	 * @return
	 */
	public Map getCompanyPermission(Map map) {
		StringUtil.checkIsTrue(map, "company", "未获取到公司");
		Map retrunMap=new HashMap();
		List<PermissionBean> allPermission=this.querryAllPermission();
		Set<String> companyHavePermissionIdSet= permissionMapper.getCompanyHavePermissionId(map.get("company").toString());
		retrunMap.put("havePermission", allPermission.stream().filter(pp->companyHavePermissionIdSet.contains(pp.getId())).collect(Collectors.toList()));
		retrunMap.put("notHavePermission", allPermission.stream().filter(pp->!companyHavePermissionIdSet.contains(pp.getId())).collect(Collectors.toList()));
		return retrunMap;
	}

	/**
	 * company
	 * permissionIdArray
	 * @param map
	 * @return
	 */
	public String setCompanyPermission(Map map) {
		StringUtil.checkIsTrue(map, "company", "未获取到公司");
		StringUtil.checkIsTrue(map, "permissionIdArray", "未获取到权限id");
		String permissionIdStr=map.get("permissionIdArray").toString();
		JSONArray jsonArray=JSONArray.fromObject(permissionIdStr);
		List<String> permissionIdList=jsonArray.subList(0, jsonArray.size());
		permissionMapper.deleteCompanyPermission(map);
		if(permissionIdList.size()>0) {
			map.put("permissionIdList", permissionIdList);
			int  row=permissionMapper.addCompanyPermission(map);
		}
		return ReturnStringUtil.SET_SUCCESS;
	}


	
}
